package com.zmn.plat.business.impl.base.maintainitem;

import com.alibaba.fastjson.JSONArray;
import com.zmn.common.dto.VtDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.plat.business.interfaces.base.maintainitem.MaintainItemBService;
import com.zmn.plat.common.dictionary.PlatErrorCodeDict;
import com.zmn.plat.common.dto.base.MaintainItemDRO;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.base.maintainitem.MaintainItem;
import com.zmn.plat.model.entity.base.phenomenon.PhenomenonMaintain;
import com.zmn.plat.model.entity.base.phenomenon.PhenomenonMaintainQuery;
import com.zmn.plat.services.interfaces.base.maintainitem.MaintainItemService;
import com.zmn.plat.services.interfaces.base.phenomenon.PhenomenonMaintainService;
import com.zmn.plat.services.interfaces.base.phenomenon.PhenomenonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 描述: 检修项目业务实现类
 *
 * @author chengguang
 * @since 2021/11/25 17:54
 */
@Slf4j
@Service
public class MaintainItemBServiceImpl implements MaintainItemBService {

    @Resource
    private PhenomenonMaintainService phenomenonMaintainService;

    @Resource
    private MaintainItemService maintainItemService;

    @Resource
    private PhenomenonService phenomenonService;

    @Override
    @Cacheable(cacheNames = "redis10m", key = "'base:listMaintainItemByPhenIds:phenIds:'+#p0", unless = "#result == null")
    public List<MaintainItemDRO> listMaintainItemByPhenIds(List<Integer> phenIds) {

        if (CollectionUtil.isNullOrEmpty(phenIds)) {
            log.error("PhenomenonBServiceImpl.listMaintainItemByPhenIds入参为空,phenIds={}", phenIds);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_PANAM_NULL);
        }
        // 根据故障现象id 查询故障现象-检修项目关联
        List<PhenomenonMaintain> phenomenonMaintains = phenomenonMaintainService.listByQuery(PhenomenonMaintainQuery.builder().phenIds(phenIds).build());
        if (CollectionUtil.isNullOrEmpty(phenomenonMaintains)) {
            log.error("PhenomenonBServiceImpl.listMaintainItemByPhenIds未查到故障现象-检修项目关联,phenIds={}", phenIds);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_RESULT_NULL);
        }

        List<MaintainItemDRO> maintainItemList = new ArrayList<>();
        // 根据故障现象-检修项目关联获取全部检修项目ids
        List<Integer> deteIds = phenomenonMaintains.stream().map(PhenomenonMaintain::getMaintainId).distinct().collect(Collectors.toList());
        // 查询全部检修项详情
        List<MaintainItem> maintainItems = maintainItemService.listByIds(deteIds);
        if (CollectionUtil.isNullOrEmpty(maintainItems)) {
            log.error("PhenomenonBServiceImpl.listMaintainItemByFaultPhenIds未查到故障现象关联检修项目,phenIds={}", phenIds);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_RESULT_NULL);
        }
        maintainItems.stream().filter(e -> Objects.equals(GlobalConsts.YES, e.getStatus())).forEach(e->{
            MaintainItemDRO maintainItemDro = new MaintainItemDRO();
            BeanUtils.copyProperties(e, maintainItemDro);
            String selectValue = e.getSelectValue();
            if (StringUtil.isNotBlank(selectValue)) {
                List<VtDTO> vts = JSONArray.parseArray(selectValue, VtDTO.class);
                maintainItemDro.setSelectValue(vts);
                maintainItemList.add(maintainItemDro);
            }
        });
        return maintainItemList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByKey(MaintainItem maintainItem) {

        if (StringUtil.isNotBlank(maintainItem.getMaintainName())) {
            //修改关联表数据
            phenomenonMaintainService.updateMaintainNameByMaintainId(maintainItem.getMaintainId(), maintainItem.getMaintainName());
        }
        maintainItemService.updateByKey(maintainItem);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatusBatch(List<Integer> maintainIds, Integer status, String mcStaffRealName) {

        if (GlobalConsts.NO == status) {
            // 获取影响的故障现象id
            List<Integer> phenIds = phenomenonMaintainService.listByQuery(PhenomenonMaintainQuery.builder()
                    .maintainIds(maintainIds).build()).stream().map(PhenomenonMaintain::getPhenId).distinct().collect(Collectors.toList());
            // 状态取消，删除故障现象关联的检修项目
            phenomenonMaintainService.deleteByMaintainIds(maintainIds);
            List<PhenomenonMaintain> phenomenonMaintains = phenomenonMaintainService.listByQuery(PhenomenonMaintainQuery.builder()
                    .phenIds(phenIds).build());
            if (CollectionUtil.isNullOrEmpty(phenomenonMaintains)) {
                phenomenonService.updateStatusBatch(phenIds, GlobalConsts.NO, mcStaffRealName);
            } else {
                List<Integer> updateStatusMaintainIds = new ArrayList<>();
                // 根据现象id分组
                Map<Integer, List<PhenomenonMaintain>> phenomenonMaintainMap = phenomenonMaintains.stream().collect(Collectors.groupingBy(PhenomenonMaintain::getPhenId));
                phenIds.forEach(phenId -> {
                    if (CollectionUtil.isNullOrEmpty(phenomenonMaintainMap)) {
                        updateStatusMaintainIds.add(phenId);
                    }
                });
                if (CollectionUtil.isNotNullOrEmpty(updateStatusMaintainIds)) {
                    phenomenonService.updateStatusBatch(updateStatusMaintainIds, GlobalConsts.NO, mcStaffRealName);
                }
            }
        }
        maintainItemService.updateStatusBatch(maintainIds, status, mcStaffRealName);
    }
}
